import { app, shell, screen, BrowserWindow, dialog, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import xlsx from 'xlsx'
const fs = require('fs')
import dayjs from 'dayjs'

function createWindow() {
  // Create the browser window.
  let size = screen.getPrimaryDisplay().workAreaSize
  let width = parseInt(size.width * 0.7)
  let height = parseInt(size.height * 0.7)
  const mainWindow = new BrowserWindow({
    width: width,
    height: height,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  if (is.dev) mainWindow.webContents.openDevTools()
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.

ipcMain.handle('readExcel', async (event) => {
  const { filePaths } = await dialog.showOpenDialog({})
  let workbook = xlsx.readFile(filePaths[0])
  let sheetNames = workbook.SheetNames
  const infos = {}
  for (let index = 0; index < sheetNames.length; index++) {
    const sheetName = sheetNames[index]
    infos[sheetName] = []
    // 获取第一个workSheet
    let sheet1 = workbook.Sheets[sheetName]
    let range = xlsx.utils.decode_range(sheet1['!ref'])

    //循环获取单元格值
    for (let R = range.s.r; R <= range.e.r; ++R) {
      infos[sheetName].push([])
      for (let C = range.s.c; C <= range.e.c; ++C) {
        let cell_address = { c: C, r: R } //获取单元格地址
        let cell = xlsx.utils.encode_cell(cell_address) //根据单元格地址获取单元格
        //获取单元格值
        if (sheet1[cell]) {
          // 如果出现乱码可以使用iconv-lite进行转码
          // row_value += iconv.decode(sheet1[cell].v, 'gbk') + ", ";
          infos[sheetName][R].push(sheet1[cell].v)
        }
      }
    }
  }
  return infos
})
ipcMain.on('writeExcel', async (event, data) => {
  const jsonData = JSON.parse(data)
  // 将数据转成workSheet
  const headers = []
  const works = {}
  for (const key in jsonData.items) {
    headers.push(key)
    works[key] = xlsx.utils.json_to_sheet(jsonData.items[key])
  }
  // 构造workBook
  let workBook = {
    SheetNames: headers,
    Sheets: works
  }
  // 将workBook写入文件
  await ensureDirExists('./save')
  if (jsonData.title === '手动保存') {
    xlsx.writeFile(workBook, `./save/${jsonData.title}_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`)
  } else {
    xlsx.writeFile(workBook, `./save/${jsonData.title}_${dayjs().format('YYYYMMDDHH')}.xlsx`)
  }
})

function ensureDirExists(dirPath) {
  return new Promise((resolve, reject) => {
    fs.access(dirPath, (err) => {
      if (err) {
        fs.mkdir(dirPath, (err) => {
          if (err) {
            reject(err)
          } else {
            resolve(true)
          }
        })
      } else {
        resolve(true)
      }
    })
  })
}
